<template>
  <div class="main">
    <div id="cesiumContainer"></div>
  </div>
</template>

<script>
var Cesium = require("cesium/Cesium");
import "../../../node_modules/cesium/Source/Widgets/widgets.css";
import $ from "jquery"
export default {
  name:"Map",
  data() {
    return {
      viewer: "",
      position: "",
      center: "",
      reBbox : {//大余县外接矩形的Bbox
        minx: 114.00029582000024,
        miny: 25.256412020000132,
        maxx: 114.68747202800001,
        maxy: 25.623771009999994,
      },
      extend:{},//屏幕可视范围的东西南北
      length:"",//切分出来的每个小网格的高
      cameraHeight: "", //相机的高度
      width:"",//切分出来的每个小网格的宽
      removeKey:[],
    };
  },
  mounted() {
    var that = this;
    Cesium.Ion.defaultAccessToken =
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4MTFmZTI3MC1hZTE0LTRmYzctYTIwMy1lMjQ1ZjgxMGRhM2UiLCJpZCI6NzI4ODQsImlhdCI6MTYzNjQ0MjcyNH0.i6q-HiknfKeuLMD-rMBZ751jBnSCzqC0nHtDpZkaBu0";
      // WebMapServiceImageryProvider
      // ArcGisMapServerImageryProvider
    let maplayer = new Cesium.ArcGisMapServerImageryProvider({
      url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
      
    });
    this.viewer = new Cesium.Viewer("cesiumContainer", {
      animation: false, //是否显示动画插件
      shouldAnimation: false, //是否自动显示动画（下方时间轴是不是在走着）
      homeButton: false, //是否显示home按钮
      fullscreenButton: false, // 是否显示全屏按钮
      baseLayerPicker: false, // 是否显示图层选择控件
      geocoder: false, // 是否显示地名查找控件
      timeline: false, // 是否显示时间线控件
      sceneModePicker: false, // 是否显示投影方式控件（右上角的小圆球）
      navigationHelpButton: false, // 是否显示帮助信息控件
      infoBox: false, // 是否显示点击要素之后显示的信息
      sceneMode: 3, // 初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
      selectionIndicator: false, //选中指示框
      navigationInstructionsInitiallyVisible: false, // 帮助按钮，初始化的时候是否展开
      mapProjection: new Cesium.WebMercatorProjection(), //地图投影体系
      terrainProvider: Cesium.createWorldTerrain(), //地形图层提供者，仅baseLayerPicker设为false有意义
      contextOptions: {
        webgl: {
          alpha: true,
          depth: true,
          stencil: true,
          antialias: true,
          premultipliedAlpha: true,
          //通过canvas.toDataURL()实现截图需要将该项设置为true
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: true,
        },
      },
    });
    this.viewer.scene.imageryLayers.addImageryProvider(maplayer); //去除谷歌请求
    // this.viewer.imageryLayers.addImageryProvider(annLayer); //图层类型的添加
    this.viewer.imageryLayers.get(0).show = true; //添加图层
    this.viewer._cesiumWidget._creditContainer.style.display = "none"; // 去除版权信息
    // this.viewer.scene.globe.depthTestAgainstTerrain = true; //地形遮挡(深度监测)
    this.viewer.scene.globe.enableLighting = false; //是否使用地球光照
    this.viewer.scene.globe.showGroundAtmosphere = false; //绘制在地球上的地面大气。
    this.viewer.terrainProvider = Cesium.createWorldTerrain({
      //启用地形照明和水体效果
      requestWaterMask: true,
      requestVertexNormals: true,
    });
    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(114.352497, 25.401622, 1500),
      orientation: {
        heading: Cesium.Math.toRadians(0.0),
        pitch: Cesium.Math.toRadians(-90.0),
        roll: Cesium.Math.toRadians(0.0),
      },
      duration: 5, //飞行时间value
    });
    this.addListener();
    // this.grid()
  },
  methods: {
    addListener() {
      var dataMap = new Map()
      var that = this
      var url2 = "http://112.94.21.83:25015/geoserver/cite/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cite%3Adayu_building_merge1&outputFormat=application%2Fjson";
      var bl=0//记录移动的次数
      // that.viewer.camera.changed.addEventListener(function(){//监听相机移动
      // this.viewer.scene.postRender.addEventListener(function(){//实时监听地图
      that.viewer.scene.camera.moveEnd.addEventListener(function(){//相机移动结束开始加载
        let remove = []//当前可视范围内所有网格的编号
        that.cameraHeight = that.viewer.camera.positionCartographic.height
        if(that.cameraHeight<2500){
          // 获取可视范围
          var rectangle = {};
          that.extend = that.viewer.camera.computeViewRectangle(); //可视范围
          rectangle.minx = Cesium.Math.toDegrees(that.extend.west);
          rectangle.miny = Cesium.Math.toDegrees(that.extend.south);
          rectangle.maxx = Cesium.Math.toDegrees(that.extend.east);
          rectangle.maxy = Cesium.Math.toDegrees(that.extend.north);
          var bbox = rectangle.minx+","+rectangle.miny+","+rectangle.maxx+","+rectangle.maxy
          // console.log(bbox)
          $.ajax({
            url:url2,
            data:{
              bbox:bbox
            },
            async:false,//设置请求为同步请求
            type:"get",
            success:function(res){
              var datasource2 = Cesium.GeoJsonDataSource.load(res);
              datasource2.then(function(source){
                that.viewer.dataSources.add(source)
              })
            }
          })
          console.log(that.viewer.dataSources._dataSources.length)
          if(that.viewer.dataSources._dataSources.length>1){
            setTimeout(()=>{
              that.viewer.dataSources.remove(that.viewer.dataSources._dataSources[0])
            },3000)
          }
        }
      })
    },
  },
};
</script>

<style>
head {
  height: 0;
  margin: 0;
}
html,
body,
#app,
.main,
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  font-family: sans-serif;
}
</style>